
// 座位选择页面JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // 初始化座位选择功能
    initSeatSelection();
    
    // 初始化楼层切换
    initFloorTabs();
    
    // 初始化日期时间选择
    initDateTimeSelection();
    
    // 添加动画效果
    addSeatSelectionAnimations();
});

// 初始化座位选择功能
function initSeatSelection() {
    const seats = document.querySelectorAll('.seat.available');
    const selectedSeatDetails = document.getElementById('selected-seat-details');
    const confirmButton = document.getElementById('confirm-booking');
    let selectedSeats = [];
    
    seats.forEach(seat => {
        seat.addEventListener('click', function() {
            // 切换选中状态
            this.classList.toggle('selected');
            const seatId = this.getAttribute('data-seat');
            
            if (this.classList.contains('selected')) {
                // 添加到选中列表
                selectedSeats.push(seatId);
            } else {
                // 从选中列表移除
                selectedSeats = selectedSeats.filter(id => id !== seatId);
            }
            
            // 更新选中座位信息
            updateSelectedSeatsInfo();
        });
    });
    
    // 更新选中座位信息
    function updateSelectedSeatsInfo() {
        if (selectedSeats.length > 0) {
            selectedSeatDetails.innerHTML = '';
            
            selectedSeats.forEach(seatId => {
                const seatItem = document.createElement('div');
                seatItem.className = 'selected-seat-item';
                seatItem.innerHTML = `
                    <span class="selected-seat-label">座位号：</span>
                    <span class="selected-seat-value">${seatId}</span>
                `;
                selectedSeatDetails.appendChild(seatItem);
            });
            
            // 添加预约时间信息
            const date = document.getElementById('booking-date').value;
            const timeSelect = document.getElementById('booking-time');
            const timeOption = timeSelect.options[timeSelect.selectedIndex].text;
            
            const dateItem = document.createElement('div');
            dateItem.className = 'selected-seat-item';
            dateItem.innerHTML = `
                <span class="selected-seat-label">预约日期：</span>
                <span class="selected-seat-value">${formatDate(date)}</span>
            `;
            
            const timeItem = document.createElement('div');
            timeItem.className = 'selected-seat-item';
            timeItem.innerHTML = `
                <span class="selected-seat-label">预约时间：</span>
                <span class="selected-seat-value">${timeOption}</span>
            `;
            
            selectedSeatDetails.appendChild(dateItem);
            selectedSeatDetails.appendChild(timeItem);
            
            // 启用确认按钮
            confirmButton.disabled = false;
        } else {
            selectedSeatDetails.innerHTML = '<p class="no-seat-selected">请选择一个座位</p>';
            confirmButton.disabled = true;
        }
    }
    
    // 确认预约按钮点击事件
    confirmButton.addEventListener('click', function() {
        if (selectedSeats.length > 0) {
            // 模拟预约提交
            showToast('正在提交预约...', 'info');
            
            setTimeout(() => {
                showToast('预约成功！', 'success');
                
                // 重置选中状态
                setTimeout(() => {
                    window.location.href = 'booking-management.html';
                }, 1500);
            }, 1500);
        }
    });
}

// 初始化楼层切换
function initFloorTabs() {
    const floorTabs = document.querySelectorAll('.floor-tab');
    const seatMap = document.querySelector('.seat-map');
    
    floorTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有活跃状态
            floorTabs.forEach(t => t.classList.remove('active'));
            
            // 添加当前活跃状态
            this.classList.add('active');
            
            const floor = this.getAttribute('data-floor');
            
            // 模拟楼层切换加载
            seatMap.style.opacity = '0.6';
            
            setTimeout(() => {
                // 更新座位地图（在实际项目中，这里可以根据楼层加载不同的座位布局）
                updateSeatMapByFloor(floor);
                
                seatMap.style.opacity = '1';
                showToast(`已切换到${floor}楼`, 'info');
            }, 500);
        });
    });
}

// 根据楼层更新座位地图
function updateSeatMapByFloor(floor) {
    // 模拟不同楼层的座位布局变化
    const seats = document.querySelectorAll('.seat');
    
    // 随机改变一些座位的状态
    seats.forEach(seat => {
        // 重置所有座位
        seat.className = 'seat available';
        
        // 随机设置一些座位为已占用或不可用
        const random = Math.random();
        if (random < 0.3) {
            seat.className = 'seat occupied';
        } else if (random > 0.9) {
            seat.className = 'seat disabled';
        }
    });
    
    // 更新区域标签
    const areaLabels = document.querySelectorAll('.area-label');
    areaLabels.forEach(label => {
        label.textContent = `${floor}楼前台`;
    });
}

// 初始化日期时间选择
function initDateTimeSelection() {
    const dateInput = document.getElementById('booking-date');
    const timeSelect = document.getElementById('booking-time');
    
    // 设置默认日期为今天
    const today = new Date().toISOString().split('T')[0];
    dateInput.value = today;
    dateInput.min = today;
    
    // 日期变更事件
    dateInput.addEventListener('change', function() {
        // 检查是否选择了过去的日期
        if (this.value < today) {
            showToast('不能选择过去的日期', 'error');
            this.value = today;
            return;
        }
        
        // 模拟根据日期更新座位状态
        updateSeatsByDate(this.value);
        showToast(`已切换到${formatDate(this.value)}`, 'info');
    });
    
    // 时间段变更事件
    timeSelect.addEventListener('change', function() {
        // 模拟根据时间段更新座位状态
        updateSeatsByTime(this.value);
        const selectedOption = this.options[this.selectedIndex].text;
        showToast(`已选择时间段：${selectedOption}`, 'info');
    });
}

// 根据日期更新座位状态
function updateSeatsByDate(date) {
    const seats = document.querySelectorAll('.seat.available, .seat.occupied');
    const selectedDate = new Date(date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // 周末和工作日的座位占用率不同
    const isWeekend = selectedDate.getDay() === 0 || selectedDate.getDay() === 6;
    const occupiedRate = isWeekend ? 0.5 : 0.3;
    
    seats.forEach(seat => {
        if (Math.random() < occupiedRate) {
            seat.className = 'seat occupied';
        } else {
            seat.className = 'seat available';
        }
    });
}

// 根据时间段更新座位状态
function updateSeatsByTime(time) {
    const seats = document.querySelectorAll('.seat.available, .seat.occupied');
    let occupiedRate = 0.3;
    
    // 不同时间段的座位占用率不同
    switch(time) {
        case 'morning':
            occupiedRate = 0.4;
            break;
        case 'afternoon':
            occupiedRate = 0.6;
            break;
        case 'evening':
            occupiedRate = 0.7;
            break;
        case 'all-day':
            occupiedRate = 0.2;
            break;
    }
    
    seats.forEach(seat => {
        if (Math.random() < occupiedRate) {
            seat.className = 'seat occupied';
        } else {
            seat.className = 'seat available';
        }
    });
}

// 添加座位选择动画
function addSeatSelectionAnimations() {
    // 座位悬停效果
    const seats = document.querySelectorAll('.seat');
    
    seats.forEach(seat => {
        // 添加座位加载动画
        seat.style.opacity = '0';
        seat.style.transform = 'scale(0.8)';
        seat.style.transition = 'all 0.3s ease';
    });
    
    // 逐个显示座位
    seats.forEach((seat, index) => {
        setTimeout(() => {
            seat.style.opacity = '1';
            seat.style.transform = 'scale(1)';
        }, 100 + index * 20);
    });
    
    // 添加地图区域动画
    const mapAreas = document.querySelectorAll('.map-area');
    mapAreas.forEach((area, index) => {
        area.style.opacity = '0';
        area.style.transform = 'translateY(20px)';
        area.style.transition = 'all 0.5s ease';
        
        setTimeout(() => {
            area.style.opacity = '1';
            area.style.transform = 'translateY(0)';
        }, 300 + index * 100);
    });
}

// 搜索可用座位
function searchAvailableSeats() {
    const availableSeats = document.querySelectorAll('.seat.available');
    
    if (availableSeats.length === 0) {
        showToast('当前没有可用座位', 'error');
        return;
    }
    
    // 高亮显示第一个可用座位
    const firstAvailable = availableSeats[0];
    firstAvailable.style.boxShadow = '0 0 0 3px #1890ff';
    
    // 滚动到该座位
    firstAvailable.scrollIntoView({ behavior: 'smooth', block: 'center' });
    
    // 3秒后移除高亮
    setTimeout(() => {
        firstAvailable.style.boxShadow = 'none';
    }, 3000);
    
    showToast(`找到 ${availableSeats.length} 个可用座位`, 'success');
}

// 清除所有选择
function clearAllSelections() {
    const selectedSeats = document.querySelectorAll('.seat.selected');
    selectedSeats.forEach(seat => {
        seat.classList.remove('selected');
    });
    
    const selectedSeatDetails = document.getElementById('selected-seat-details');
    selectedSeatDetails.innerHTML = '<p class="no-seat-selected">请选择一个座位</p>';
    
    const confirmButton = document.getElementById('confirm-booking');
    confirmButton.disabled = true;
    
    showToast('已清除所有选择', 'info');
}

// 获取座位统计信息
function getSeatStatistics() {
    const totalSeats = document.querySelectorAll('.seat').length;
    const availableSeats = document.querySelectorAll('.seat.available').length;
    const occupiedSeats = document.querySelectorAll('.seat.occupied').length;
    const disabledSeats = document.querySelectorAll('.seat.disabled').length;
    
    const availabilityRate = Math.round((availableSeats / totalSeats) * 100);
    
    const stats = `
        总座位数: ${totalSeats}<br>
        可用座位: ${availableSeats}<br>
        已预约: ${occupiedSeats}<br>
        不可用: ${disabledSeats}<br>
        可用率: ${availabilityRate}%
    `;
    
    // 显示统计信息
    showToast(stats, 'info', 5000);
}

// 添加键盘快捷键
function addKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + F 搜索可用座位
        if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
            e.preventDefault();
            searchAvailableSeats();
        }
        
        // Ctrl/Cmd + L 清除所有选择
        if ((e.ctrlKey || e.metaKey) && e.key === 'l') {
            e.preventDefault();
            clearAllSelections();
        }
        
        // Ctrl/Cmd + S 显示统计信息
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            getSeatStatistics();
        }
        
        // ESC 清除选择
        if (e.key === 'Escape') {
            clearAllSelections();
        }
    });
}

// 初始化键盘快捷键
addKeyboardShortcuts();

// 自适应座位大小
function adjustSeatSize() {
    const containerWidth = document.querySelector('.seat-grid').offsetWidth;
    const seatCount = document.querySelectorAll('.seat-row:first-child .seat').length;
    
    // 计算合适的座位大小
    const maxSeatSize = Math.min(60, (containerWidth - (seatCount - 1) * 15) / seatCount);
    const seatSize = Math.max(30, maxSeatSize);
    
    const seats = document.querySelectorAll('.seat');
    seats.forEach(seat => {
        seat.style.width = seatSize + 'px';
        seat.style.height = seatSize + 'px';
    });
}

// 监听窗口大小变化
window.addEventListener('resize', debounce(adjustSeatSize, 300));

// 初始化时调整座位大小
setTimeout(adjustSeatSize, 100);